<?php

namespace app\admin\controller;

use app\common\service\BalanceService;
use think\Db;

class Invest extends Common {

	public function inconfig(){

		return $this->fetch();
	}

	
	public function inconfigList(){
		$limit = request()->param('limit')?:20;
		$data  = Db::table('tp_invest_config')
				->paginate($limit);
		$data = $data->toArray();
		return $this->tableData($data);
	}

	public function level(){
		return $this->fetch();
	}

	
	public function levelList(){
		$limit = request()->param('limit')?:20;
		$data  = Db::table('tp_invest_level_config')
				->paginate($limit);
		$data = $data->toArray();
		return $this->tableData($data);
	}

	//编辑
	public function editConfig() {
		if (request()->method() == 'POST') {
			$id     = request()->param('id');
			$data   = request()->param();
			unset($data['action']);
			unset($data['func']);
			unset($data['api']);
			// $data['status'] = isset($data['status'])?1:0;
			// $data['is_open'] = isset($data['is_open'])?1:0;
			if ($id) {
				$res = Db::table('tp_invest_config')->where('id',$id)->update($data);
			} else {
				$res = Db::table('tp_invest_config')->insert($data);
			}
			if ($res) {
				return ['code' => 0, 'msg' => '操作成功'];
			} else {
				return ['code' => 1, 'msg' => '操作失败'];
			}
		} else {
			$id   = request()->param('id');
			$data = []; 
			if ($id) {
				$data = Db::table('tp_invest_config')->where('id',$id)->find();
			} else {
				$data['status']=1;
				$data['is_open']=1;
			}
			$this->assign('data',$data);
			return $this->fetch();
		}
	}

	public function delInvest(){
		$id = request()->param('id');
		$res = Db::table('tp_invest_level_config')->where('id',$id)->delete();
		if ($res) {
			return ['code'=>0,'msg'=>'successs'];
		} else {
			return ['code'=>1,'msg'=>'删除失败'];
		}
	}
	//编辑
	public function editLevel() {
		if (request()->method() == 'POST') {
			$id     = request()->param('id');
			$data   = request()->param();
			unset($data['action']);
			unset($data['func']);
			unset($data['api']);
			// $data['status'] = isset($data['status'])?1:0;
			// $data['is_open'] = isset($data['is_open'])?1:0;
			if ($id) {
				$res = Db::table('tp_invest_level_config')->where('id',$id)->update($data);
			} else {
				$res = Db::table('tp_invest_level_config')->insert($data);
			}
			if ($res) {
				return ['code' => 0, 'msg' => '操作成功'];
			} else {
				return ['code' => 1, 'msg' => '操作失败'];
			}
		} else {
			$id   = request()->param('id');
			$data = []; 
			if ($id) {
				$data = Db::table('tp_invest_level_config')->where('id',$id)->find();
			} else {
				
			}
			$this->assign('data',$data);
			return $this->fetch();
		}
	}

	public function delLevel(){
		$id = request()->param('id');
		$res = Db::table('tp_invest_level_config')->where('id',$id)->delete();
		if ($res) {
			return ['code'=>0,'msg'=>'successs'];
		} else {
			return ['code'=>1,'msg'=>'删除失败'];
		}
	}
	public function record(){
		$robot_config = Db::table('tp_invest_config')->where('id','>',0)->field('id,name')->select();
		$this->assign('robot',$robot_config);
		return $this->fetch();
	}


	public function recordList(){
		$limit = request()->param('limit') ?: 20;
		$username = request()->param('username');
		$uid = request()->param('uid');
		$config_id = request()->param('config_id');
		$status = request()->param('status');
		$is_active = request()->param('is_active');
		$start_time = request()->param('start_time');
		$end_time   = request()->param('end_time');
		$where      = '1=1';
		if ($username != '') {
            $where .= ' and u.username like \'%' . $username . '%\'';
        }
        if($status != '') {
            $where .= ' and a.status='.$status;
        }
        if($is_active != '') {
            $where .= ' and a.is_active='.$is_active;
        }
        // if($phone != '') {
        //     $where .= ' and u.phone='.$phone;
        // }
        // if($uid != '') {
        //     $where .= ' and a.uid='.$uid;
        // }
        if($uid != '') {
			if (!in_array($uid, $this->data_uids_arr)) {
				return $this->tableData([]);
			}
			$where .= ' and a.uid='.$uid;
		} else {
			if ($this->data_uids_string) {
				$where .= ' and a.uid in ('.$this->data_uids_string.')';
			}
		}
		if($config_id != '') {
            $where .= ' and a.config_id='.$config_id;
        }
  //       if ($this->data_uids) {
		// 	$where .= ' and a.uid in ('.$this->data_uids.')';
		// }
		if($start_time != '') {
            $where .= ' and a.order_date>="'.$start_time.'"';
        }
		if($end_time != '') {
            $where .= ' and a.order_date<="'.$end_time.'"';
        }
		$data = Db::table('tp_invest_record')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.username')
				->paginate($limit);
		$data = $data->toArray();
		if(empty($data['data'])){
			$data['data']  = Db::table('tp_invest_record')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.username')
				->page(1)
				->limit($limit)
				->select();		
		}
		return $this->tableData($data);
	}

	public function tq(){
		return $this->fetch();
	}

	public function tqsq(){
		return $this->fetch();
	}

	public function sqtq(){
		if (request()->method() == 'POST') {
			$data = request()->param();
			$uid   = $data['uid'];
			$type   = $data['type'];
			$amount   = $data['amount'];
			if (!in_array($type, ['11','12'])) {
				return ['code'=>1,'msg'=>'提取类型有误'];
			}
			if (!in_array($uid, $this->data_uids_arr)) {
				return ['code'=>1,'msg'=>'权限不足'];
			}
			$balance = model('UserBalanceModel')->getBalance($uid,$type);
			if ($balance < $amount) {
				return ['code'=>1,'msg'=>'用户余额不足'];
			}


			Db::startTrans();
	        $res1 = BalanceService::updateBalance($uid,$type,-$amount,'佣金转出',111);
	        $res2 = Db::table('tp_invest_tq')->insert([
	            'uid'=>$uid,
	            'amount'=>$amount,
	            'date'=>date('Y-m-d H:i:s'),
	            'type'=>$type,
	            'status'=>$this->admin_info['level'],
	            'admin_uid'=>$this->admin_info['id'],
	            'remark'=>''
	        ]);
	        if ($res1 && $res2) {
	            Db::commit();
	            return ['code'=>0,'msg'=>'发起申请成功'];
	        } else {
	            Db::rollback();
	            return ['code'=>1,'msg'=>'发起申请失败'];
	        }			
		} else {
			$id   = request()->param('id');
			return $this->fetch();
		}
	}
	
	public function tqList(){
		$limit = request()->param('limit') ?: 20;
		$username = request()->param('username');
		$uid = request()->param('uid');
		$type = request()->param('type');
		$wid = request()->param('wid');
		$status = request()->param('status');
		$is_active = request()->param('is_active');
		$where      = '1=1';
		if ($username != '') {
            $where .= ' and u.username like \'%' . $username . '%\'';
        }
        if($status != '') {
            $where .= ' and a.status='.$status;
        }
        if($is_active != '') {
            $where .= ' and a.is_active='.$is_active;
        }
        // if($phone != '') {
        //     $where .= ' and u.phone='.$phone;
        // }
         if($uid != '') {
			if (!in_array($uid, $this->data_uids_arr)) {
				return $this->tableData([]);
			}
			$where .= ' and a.uid='.$uid;
		} else {
			if ($this->data_uids_string) {
				$where .= ' and a.uid in ('.$this->data_uids_string.')';
			}
		}
		if($wid != '') {
            $where .= ' and a.wid='.$wid;
        }
  //       if ($this->data_uids) {
		// 	$where .= ' and a.uid in ('.$this->data_uids.')';
		// }
		$data = Db::table('tp_invest_tq')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->join('tp_admin m', 'm.id = a.admin_uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.username,m.name adminname')
				->paginate($limit);
		$data = $data->toArray();
		if(empty($data['data'])){
			$data['data']  = Db::table('tp_invest_tq')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->join('tp_admin m', 'm.id = a.admin_uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.username,m.name adminname')
				->page(1)
				->limit($limit)
				->select();		
		}
		return $this->tableData($data);
	}

	public function pass() {
		if (request()->method() == 'POST') {
			// if (!in_array($this->admin_info['level'], [1])) {
			// 	return ['code' => 1, 'msg' => '权限不足'];
			// }
			$data = [];
			$id = intval(request()->param('id'));
			// $remark = request()->param('value');
			
			Db::startTrans();
			$info = Db::table('tp_invest_tq')->where('id', $id)->lock(true)->find();
			if (empty($info)) {
				Db::rollback();
				return ['code' => 1, 'msg' => '订单不存在'];
			}
			if ($info['status'] <= 0) {
				Db::rollback();
				return ['code' => 1, 'msg' => '订单状态有误'];
			}
			if (!in_array($info['uid'], $this->data_uids_arr)) {
				Db::rollback();
				return ['code' => 1, 'msg' => '权限不足'];
			}
			if ($info['status'] > $this->admin_info['level']) {
				Db::rollback();
				return ['code' => 1, 'msg' => '清等待下级审核'];
			}
			if ($info['status'] < $this->admin_info['level']) {
				Db::rollback();
				return ['code' => 1, 'msg' => '请等待上级审核'];
			}
			if ($info['status'] == 1) {
				$status = 0;
				$res1 = Db::table('tp_invest_tq')->where('id', $id)->update([
					'status'=>$status
				]);
				$res2 = BalanceService::updateBalance($info['uid'],1,$info['amount'],'佣金提取转入',112);
				if ($res1 && $res2) {
					Db::commit();
					return ['code' => 0, 'msg' => '提取成功，资产已到账'];
				} else {
					Db::rollback();
					return ['code' => 1, 'msg' => '操作失败'];
			}
			} else {
				$status = $info['status'] + 1;
				$res = Db::table('tp_invest_tq')->where('id', $id)->update([
					'status'=>$status
				]);
				if (!$res) {
					Db::rollback();
					return ['code' => 1, 'msg' => '审核失败'];
				} else {
					Db::commit();
					return ['code' => 0, 'msg' => '审核成功'];
				}
			}
		}
	}

	public function refuse() {
		if (request()->method() == 'POST') {
			// if (!in_array($this->admin_info['level'], [1])) {
			// 	return ['code' => 1, 'msg' => '权限不足'];
			// }
			$data = [];
			$id = intval(request()->param('id'));
			// $remark = request()->param('value');
			
			Db::startTrans();
			$info = Db::table('tp_invest_tq')->where('id', $id)->lock(true)->find();
			if (empty($info)) {
				Db::rollback();
				return ['code' => 1, 'msg' => '订单不存在'];
			}
			if ($info['status'] <= 0) {
				Db::rollback();
				return ['code' => 1, 'msg' => '订单状态有误'];
			}
			if (!in_array($info['uid'], $this->data_uids_arr)) {
				Db::rollback();
				return ['code' => 1, 'msg' => '权限不足'];
			}
			if ($info['status'] > $this->admin_info['level']) {
				Db::rollback();
				return ['code' => 1, 'msg' => '请等待下级审核'];
			}
			if ($info['status'] < $this->admin_info['level']) {
				Db::rollback();
				return ['code' => 1, 'msg' => '请等待上级审核'];
			}
			$status = -$this->admin_info['level'];
			$res1 = Db::table('tp_invest_tq')->where('id', $id)->update([
				'status'=>$status
			]);
			$res2 = BalanceService::updateBalance($info['uid'],$info['type'],-$info['amount'],'佣金提取驳回',113);
			if ($res1 && $res2) {
				Db::commit();
				return ['code' => 0, 'msg' => '拒绝成功'];
			} else {
				Db::rollback();
				return ['code' => 1, 'msg' => '操作失败'];
			}

		}
	}


	public function profit(){
		return $this->fetch();
	}
	public function statistics(){
		return $this->fetch();
	}

	public function profitList(){
		$limit = request()->param('limit') ?: 20;
		$username = request()->param('username');
		$uid = request()->param('uid');
		$phone = request()->param('phone');
		// $start_time = request()->param('start_time');
		// $end_time   = request()->param('end_time');
		$where      = '1=1';
		if ($username != '') {
            $where .= ' and u.username like \'%' . $username . '%\'';
        }
        if($phone != '') {
            $where .= ' and u.phone='.$phone;
        }
        if($uid != '') {
            $where .= ' and a.uid='.$uid;
        }
        if ($this->data_uids) {
			$where .= ' and a.uid in ('.$this->data_uids.')';
		}
		$data = Db::table('tp_invest_profit_record')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.username')
				->paginate($limit);
		$data = $data->toArray();
		if(empty($data['data'])){
			$data['data']  = Db::table('tp_invest_profit_record')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.username')
				->page(1)
				->limit($limit)
				->select();		
		}
		return $this->tableData($data);
	}

	public function statisticsList(){
		$limit = request()->param('limit') ?: 20;
		$username = request()->param('username');
		$uid = request()->param('uid');
		$phone = request()->param('phone');
		// $start_time = request()->param('start_time');
		// $end_time   = request()->param('end_time');
		$where      = '1=1';
		if ($username != '') {
            $where .= ' and u.username like \'%' . $username . '%\'';
        }
        if($phone != '') {
            $where .= ' and u.phone='.$phone;
        }
        if($uid != '') {
            $where .= ' and a.uid='.$uid;
        }
        if ($this->data_uids) {
			$where .= ' and a.uid in ('.$this->data_uids.')';
		}
		$data = Db::table('tp_invest_statistics')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.username')
				->paginate($limit);
		$data = $data->toArray();
		if(empty($data['data'])){
			$data['data']  = Db::table('tp_invest_statistics')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.username')
				->page(1)
				->limit($limit)
				->select();		
		}
		return $this->tableData($data);
	}
	public function team(){
		return $this->fetch();
	}
	public function teamList(){
		$limit = request()->param('limit')?:20;
		$data  = Db::table('tp_invest_level_config')
				->paginate($limit);
		$data = $data->toArray();
		return $this->tableData($data);
	}
	/*
	单元格编辑
	*/
	public function editTable(){
		$id = request()->param('id');
		$field = request()->param('field');
		$value = request()->param('value');
		$type = request()->param('type');
		switch ($type) {
			case '1':
				$table = 'tp_invest_level_config';
				break;
			case '2':
				$table = 'tp_invest_zt_config1';
				break;
			case '3':
				$table = 'tp_invest_zt_config2';
				break;
			case '4':
				# code...
				break;
			default:
				# code...
				break;
		}
		$res = Db::table($table)->where('id',$id)->update([
			$field=>$value
		]);
		if($res){
			return ['code'=>0,'msg'=>'success'];
		} else {
			return ['code'=>1,'msg'=>'更新失败'];
		}
	}

	public function invite1(){
		return $this->fetch();
	}
	public function invite1List(){
		$limit = request()->param('limit')?:20;
		$data  = Db::table('tp_invest_zt_config1')
				->paginate($limit);
		$data = $data->toArray();
		return $this->tableData($data);
	}


	public function invite2(){
		return $this->fetch();
	}
	public function invite2List(){
		$limit = request()->param('limit')?:25;
		$data  = Db::table('tp_invest_zt_config2')
				->paginate($limit);
		$data = $data->toArray();
		return $this->tableData($data);
	}



	public function hashrate(){
		return $this->fetch();
	}


	public function hashrateList(){
		$limit = request()->param('limit') ?: 20;
		$username = request()->param('username');
		$uid = request()->param('uid');
		$status = request()->param('status');

		$where      = '1=1';
		if ($username != '') {
            $where .= ' and u.username like \'%' . $username . '%\'';
        }
        if($status != '') {
            $where .= ' and a.status='.$status;
        }
        // if($phone != '') {
        //     $where .= ' and u.phone='.$phone;
        // }
        if($uid != '') {
            $where .= ' and a.uid='.$uid;
        }

		$data = Db::table('tp_invest_hashrate')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.username')
				->paginate($limit);
		$data = $data->toArray();
		if(empty($data['data'])){
			$data['data']  = Db::table('tp_invest_hashrate')
				->alias('a')
				->join('tp_user u', 'u.id = a.uid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.username')
				->page(1)
				->limit($limit)
				->select();		
		}
		return $this->tableData($data);
	}


	public function active(){
		$id = request()->param('id');
		$record = Db::table('tp_invest_record')->where('id',$id)->find();
		if (empty($record)) {
			return ['code'=>1,'msg'=>'订单不存在'];
		}
		if ($record['status']==3) {
			return ['code'=>1,'msg'=>'订单已结束'];
		}
		$config = Db::table('tp_invest_config')->where('id',$record['config_id'])->find();
        $min = $config['min'];
        $balance = model('UserBalanceModel')->getBalance($record['uid'],1);
        $ty_balance = model('UserBalanceModel')->getBalance($record['uid'],10);

        $balance = $balance + $ty_balance;
        if ($balance < $min) {
            return ['code'=>1,'msg'=>'账户余额不足'];
        }
		if ($record['status'] == 1) {
			$res = Db::table('tp_invest_record')->where('id',$id)->update([
				'status'=>2,
				'open_date'=>date('Y-m-d H:i:s'),
				'open_type'=>2,
			]);
			$user_info = Db::table('tp_user')->where('id',$record['uid'])->find();
			$uid = $user_info['id'];
			//自身升级
	        if ($record['config_id'] >= 4) {
	            if ($user_info['level'] == 1) {
	                $res2 = Db::table('tp_user')->where('id',$uid)->update(['level'=>2,'vip_update_date'=>date('Y-m-d H:i:s')]);
	            }
	        }
	        $uid = $user_info['id'];
	        //上级升级
	        $is_first = Db::table('tp_invest_record')->where('uid',$uid)->where('open_type','>',0)->where('config_id','>',1)->count();
	        if ($is_first == 1) {
	            $pid = $user_info['pid'];
	            if ($pid != 0) {
	                $p_userinfo = Db::table('tp_user')->where('id',$pid)->find();
	                if ($p_userinfo['level'] < 3) {
	                	$p_config_id = Db::table('tp_invest_record')->where('uid',$pid)->where('status',2)->value('config_id');
		                if ($p_config_id >= 4) {
		                    $p_level = 2;
		                } else {
		                    $p_level = 1; 
		                }
		     
		                if ($p_userinfo['vip_next_days'] >= 10) {
		                    $vip_next_days = 10;
		                } else {
		                    $vip_next_days = $p_userinfo['vip_next_days'] + 1;
		                }

		                if ($p_userinfo['level'] >= 1) {
		                	$res3 = Db::table('tp_user')->where('id',$pid)->update([
			                    'level'=>$p_level,
			                    'vip_date'=>date('Y-m-d H:i:s',strtotime($p_userinfo['vip_date'])+86400*$vip_next_days),
			                    'vip_next_days'=>$vip_next_days,
			                    'vip_update_date'=>date('Y-m-d H:i:s')
			                ]);
		                } else {
		                	$res3 = Db::table('tp_user')->where('id',$pid)->update([
			                    'level'=>$p_level,
			                    'vip_date'=>date('Y-m-d H:i:s',strtotime('+5 days')),
			                    'vip_next_days'=>6,
			                    'vip_update_date'=>date('Y-m-d H:i:s')
			                ]);
		                }
		                

		                //上级体验金
		                $num = Db::table('tp_invest_record')->alias('a')
		                    ->join('tp_user b','b.id=a.uid and b.pid='.$pid)
		                    ->where('a.config_id','>',1)
		                    ->where('a.status','in','2,3,4')
		                    ->group('a.uid')
		                    ->count();
		                if ($num >= 3) {
		                    $ty_balance = model('UserBalanceModel')->getBalance($pid,10);
		                    if ($ty_balance > 0 ) {
		                        if ($ty_balance > 10) {
		                            $ty_balance = 10;
		                        }
		                        $res4 = BalanceService::updateBalance($pid,10,-$ty_balance,'体验金转出',91);
		                        $res5 = BalanceService::updateBalance($pid,1,$ty_balance,'体验金转入',92);
		                    }  
		                }
	                }
	            }
	        }
	        
			if($res){
				return ['code'=>0,'msg'=>'开启成功'];
			} else {
				return ['code'=>1,'msg'=>'开启失败'];
			}
		} else if($record['status'] == 2) {
			$res = Db::table('tp_invest_record')->where('id',$id)->update([
				'status'=>1,
				'close_date'=>date('Y-m-d H:i:s'),
				'close_type'=>2,
			]);
			if($res){
				return ['code'=>0,'msg'=>'关闭成功'];
			} else {
				return ['code'=>1,'msg'=>'关闭失败'];
			}
		}
		
	}


	public function rate(){
		$data = Db::table('tp_invest_config')->select();
		$this->assign('robot',$data);
		return $this->fetch();
	}

	public function rateList(){
		$limit = request()->param('limit') ?: 20;
		// $username = request()->param('username');
		$config_id = request()->param('config_id');

		$where      = '1=1';

        if($config_id != '') {
            $where .= ' and a.rid='.$config_id;
        }

		$data = Db::table('tp_invest_config_rate')
				->alias('a')
				->join('tp_invest_config u', 'u.id = a.rid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.name')
				->paginate($limit);
		$data = $data->toArray();
		if(empty($data['data'])){
			$data['data']  = Db::table('tp_invest_config_rate')
				->alias('a')
				->join('tp_invest_config u', 'u.id = a.rid', 'LEFT')
				->where($where)
				->order('a.id desc')
				->field('a.*,u.name')
				->page(1)
				->limit($limit)
				->select();		
		}
		return $this->tableData($data);
	}

	public function addRate(){
		if (request()->method() == 'POST') {
			$id     = request()->param('id');
			$data   = request()->param();
			unset($data['action']);
			unset($data['func']);
			unset($data['api']);
			// $data['status'] = isset($data['status'])?1:0;
			// $data['is_open'] = isset($data['is_open'])?1:0;
			if ($id) {
				$res = Db::table('tp_invest_config_rate')->where('id',$id)->update($data);
			} else {
				$res = Db::table('tp_invest_config_rate')->insert($data);
			}
			if ($res) {
				return ['code' => 0, 'msg' => '操作成功'];
			} else {
				return ['code' => 1, 'msg' => '操作失败'];
			}
		} else {
			$data = Db::table('tp_invest_config')->select();
			$this->assign('robot',$data);
			return $this->fetch();
		}
	}
}
